package com.hulk.dryad.manage.boot.basic.error;

import com.hulk.dryad.common.component.R;
import com.hulk.dryad.common.constant.enums.BEC;
import org.hibernate.validator.internal.engine.path.PathImpl;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import javax.validation.ConstraintViolation;
import java.util.Set;


/**
 * 抽取共性 通用部分代码
 *
 * @author hulk
 */
public abstract class BaseExceptionTranslator {

	/**
	 * 处理 BindingResult
	 * @param result BindingResult
	 * @return R
	 */
	protected R<Object> handleError(BindingResult result) {
		FieldError error = result.getFieldError();
		//String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
		String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
		return  R.failed(BEC.E_2020.getErrCode(),BEC.E_2020.getErrDesc()+":"+message) ;
	}

	/**
	 * 处理 ConstraintViolation
	 * @param violations 校验结果
	 * @return R
	 */
	protected R<Object> handleError(Set<ConstraintViolation<?>> violations) {
		ConstraintViolation<?> violation = violations.iterator().next();
		//String message = e.getConstraintViolations().stream().map(javax.validation.ConstraintViolation::getMessage).collect(Collectors.joining());
		String path = ((PathImpl) violation.getPropertyPath()).getLeafNode().getName();
		String message = String.format("%s:%s", path, violation.getMessage());
		return  R.failed(BEC.E_2020.getErrCode(),BEC.E_2020.getErrDesc()+":"+message) ;
	}
}
